import json
from django.http import JsonResponse, HttpResponse
from rest_framework import viewsets
from rest_framework.decorators import action
from .serializers import *
import time
import requests
import hashlib
from pyecharts import options as opts
from pyecharts.charts import Line, Pie, WordCloud
import pandas
import jieba.analyse

# __imagehttpbase__ = 'http://demoapi.qyin.top/static'
__imagehttpbase__ = 'http://127.0.0.1:8050/static'

def chartpie(request):
    level = MallGoodsCategory.objects.filter(category_level = 1)
    level2 = []
    level3 = []
    for i in level:
        level2.append(i.category_name)
        level3.append(MallGoodsCategory.objects.filter(parent_id = i.pk).count())
    pie = Pie()
    pie.add("", [(level2[i], level3[i]) for i in range(len(level))])
    # pie.set_global_opts(title_opts=opts.TitleOpts(title="分类分布图展示", subtitle="此分类图由二级分类以及三级分类生成"))
    return HttpResponse(pie.render_embed())

def chartline(request):
    level = MallGoodsCategory.objects.filter(category_level = 2)
    level2 = []
    level3 = []
    for i in level:
        level2.append(i.category_name)
        if MallGoodsCategory.objects.filter(parent_id=i.pk).count() == 0:
            num = str(time.time())[-2:-1]
            level3.append(int(num))
        else:
            level3.append(MallGoodsCategory.objects.filter(parent_id = i.pk).count())
    chart = Line()
    chart.add_xaxis(level2)
    chart.add_yaxis('', level3, is_smooth = False,
        symbol="emptyCircle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=False),
        areastyle_opts=opts.AreaStyleOpts(opacity=1, color="#C67570"),)
    chart.set_global_opts(
        title_opts=opts.TitleOpts(title="商品关注度分布", subtitle="此折线图由二级分类以及三级分类生成"),
        datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
    )
    # pie.set_global_opts(title_opts=opts.TitleOpts(title="分类分布图展示", subtitle="此分类图由二级分类以及三级分类生成"))
    return HttpResponse(chart.render_embed())

def chartwordcloud(request):
    goods = MallGoodsInfo.objects.all()
    segments = []
    for i in goods:
        content = i.goods_name
        # TextRank 关键词抽取，只获取固定词性
        words = jieba.analyse.textrank(content, topK=50, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'))
        splitedStr = ''
        for word in words:
            # 记录全局分词
            segments.append({'word': word, 'count': 1})
            splitedStr += word + ' '
    dfSg = pandas.DataFrame(segments)
    # 词频统计
    dfWord = dfSg.groupby('word')['count'].sum()
    df = dfWord.to_frame()
    words = []
    for k, v in df.iterrows():
        words.append((k, int(v['count'])))
    chart = WordCloud()
    chart.add('', words)
    chart.set_global_opts(title_opts=opts.TitleOpts(title="商品词云图", subtitle="由所有商品名字取关键字生成"))
    return HttpResponse(chart.render_embed())




def DO_AlyPay(para_list):
    partner = "1000"
    key = "WBZHZWBeheKhWZcKuGRlb8lKWzwCWUeH"
    notify_url = "http://demoapi.qyin.top/goods-api/"
    return_url = "http://qyin.top"
    sitename = 'MYWEB.COM'

    para_list['pid'] = partner
    para_list['notify_url'] = notify_url
    para_list['return_url'] = return_url
    para_list['sitename'] = sitename
    para_list['sign'] = ""
    para_list['sign_type'] = "MD5"

    # 生成签名
    para_list_filter = {}  # sign、sign_type、和空值不参与签名
    for k, v in para_list.items():
        if k == "sign" or k == "sign_type" or v == "":
            continue
        else:
            para_list_filter[k] = v

    # 按照ASCII码从小到大排序（a-z）
    para_list_sorted = sorted(para_list_filter)

    para_str = ""  # 组成a=b&c=d&e=f，参数值不要进行url编码
    for k in para_list_sorted:
        para_str += "&" + k + "=" + para_list_filter[k]

    sign_str = para_str[1:] + key  # 拼接好的字符串与商户密钥KEY进行MD5加密得出sign签名参数
    sign = hashlib.md5(sign_str.encode(encoding='utf-8')).hexdigest()

    para_list['sign'] = sign  # 将sign写入post 提交参数

    # 提交api
    url = "https://cc.liyunfupay.cn/mapi.php"
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    response_result = requests.post(url, data=(para_list), headers=headers)
    # status_code = response_result.status_code
    response_text = eval(response_result.text)

    # print(response_text)
    code = response_text['code']
    trade_no = response_text['trade_no']
    payurl = response_text['payurl']

    if code != 1:
        return {'ret': response_text['code']}

    return payurl


def newDate():
    return  time.strftime("%Y-%m-%d %H:%M", time.localtime())
"""


class ViewSet(viewsets.ModelViewSet):
    queryset = .objects.all()
    serializer_class = Serializer
"""


class MallOrderViewSet(viewsets.ModelViewSet):
    queryset = MallOrder.objects.all()
    serializer_class = MallOrderSerializer

class OrderAddressViewSet(viewsets.ModelViewSet):
    queryset = OrderAddress.objects.all()
    serializer_class = OrderAddressSerializer

class OrderItemViewSet(viewsets.ModelViewSet):
    queryset = OrderItem.objects.all()
    serializer_class = OrderItemSerializer

class UserAddressViewSet(viewsets.ModelViewSet):
    queryset = UserAddress.objects.all()
    serializer_class = UserAddressSerializer

class UserTokenViewSet(viewsets.ModelViewSet):
    queryset = UserToken.objects.all()
    serializer_class = UserTokenSerializer

class MallUserViewSet(viewsets.ModelViewSet):
    queryset = MallUser.objects.all()
    serializer_class = MallUserSerializer

class UserinfoViewSet(viewsets.ModelViewSet):
    serializer_class = MallUserSerializer
    @action(methods=['POST'], detail=False, url_name='userinfo')
    def getUser(self, request, id, pwd):
        queryset = MallUser.objects.filter(login_name=id, user_pwd=pwd).first()
        if queryset:
            return JsonResponse({'status': 200, 'data': queryset.nick_name, 'message': 'ok'}, safe=False)
        else:
            return JsonResponse({'status': 555, 'data': [], 'message': '账号或密码错误！'})

class UserzhuceViewSet(viewsets.ModelViewSet):
    serializer_class = MallUserSerializer
    @action(methods=['POST'], detail=False, url_name='userzhuce')
    def zhuceUser(self, request, id, pwd, nick):
        queryset = MallUser.objects.filter(login_name=id, nick_name=nick).first()
        if queryset:
            return JsonResponse({'status': 500, 'message': '用户名或者昵称重复！'})
        else:
            queryset = MallUser.objects.create(login_name=id, user_pwd=pwd, nick_name=nick, locked=0, is_deleted=0,
                                               create_time=newDate())
            if queryset:
                return JsonResponse({'status': 201, 'data': queryset.nick_name, 'message': 'ok'}, safe=False)
            else:
                return JsonResponse({'status': 500, 'message': '服务器内部错误，请联系管理员！'})


class MallCommentViewSet(viewsets.ModelViewSet):
    queryset = MallComment.objects.all()
    serializer_class = MallCommentSerializer

class MallCartViewSet(viewsets.ModelViewSet):
    queryset = MallCart.objects.all()
    serializer_class = MallCartSerializer

class MallGoodsCategoryViewSet(viewsets.ModelViewSet):
    serializer_class = MallGoodsCategorySerializer
    @action(methods=['GET'], detail=False, url_name='goods_category')
    def defined(self, request, num):
        try:
            query = MallGoodsCategory.objects.filter(category_level = 1)
            newlist = []
            for i in query:
                newdist = {}
                newdist['id'] = i.pk
                newdist['name'] = i.category_name
                # newdist['level2'] = []
                # newdist['img'] = __imagehttpbase__ + i.goods_cover_img
                if int(num) == 0:
                    num= query[0].pk
                if i.pk == int(num):
                    query = MallGoodsCategory.objects.filter(parent_id = num)
                    newdist['level2'] = []
                    for i in query:
                        newdist2 = {}
                        newdist2['name'] = i.category_name
                        newdist2['level3'] = []
                        query = MallGoodsCategory.objects.filter(parent_id= i.pk)
                        for i in query:
                            newdist3 = {}
                            newdist3['name'] = i.category_name
                            newdist2['level3'].append(newdist3)
                        newdist['level2'].append(newdist2)
                newlist.append(newdist)
            return JsonResponse({'status': 200, 'data': newlist, 'message': 'ok'})
        except:
            return JsonResponse({'status': 556, 'message': '出现问题请联系管理员！'})

class MallGoodsInfoViewSet(viewsets.ModelViewSet):
    serializer_class = MallGoodsInfoSerializer
    @action(methods=['GET'], detail=False, url_name='goodsconfig')
    def defined(self, request, name):
        try:
            query = MallGoodsInfo.objects.filter(goods_name__contains= name).order_by('selling_price')
            newlist = []
            for i in query:
                newdist = {}
                newdist['id'] = i.pk
                newdist['name'] = i.goods_name
                newdist['selling_price'] = i.selling_price
                newdist['original_price'] = i.original_price
                newdist['img'] = __imagehttpbase__ + i.goods_cover_img
                newlist.append(newdist)
            return JsonResponse({'status': 200, 'data': newlist, 'message': 'ok'})
        except:
            return JsonResponse({'status': 556, 'message': '出现问题请联系管理员！'})

class MallCarouselViewSet(viewsets.ModelViewSet):
    serializer_class = MallCarouselSerializer
    @action(methods=['GET'], detail=False, url_name='config')
    def defined(self, request):
        newlist = []
        queryset = MallCarousel.objects.all()
        for i in queryset:
            newdist = {}
            newdist['img'] = __imagehttpbase__ + str(i.carousel_url)
            newlist.append(newdist)
        return JsonResponse({'status': 200, 'data': newlist, 'message': 'ok'}, safe=False)

class MallIndexConfigViewSet(viewsets.ModelViewSet):
    serializer_class = MallIndexConfigSerializer
    @action(methods=['GET'], detail=False, url_name='config')
    def defined(self, request):
        newlist = []
        queryset = MallIndexConfig.objects.all()
        for i in queryset:
            newdist = {}
            newdist['name'] = i.config_name
            newdist['type'] = i.config_type
            newlist.append(newdist)
        return JsonResponse({'status': 200, 'data': newlist, 'message': 'ok'}, safe=False)


class HomeInfoViewSet(viewsets.ModelViewSet):
    serializer_class = MallIndexConfigSerializer
    @action(methods=['GET'], detail=False, url_name='homeinfo')
    def defined(self, request, type, third):
        newlist = []
        queryset = MallIndexConfig.objects.filter(config_type=type)
        for i in queryset:
            newdist = {}
            newdist['name'] = i.config_name
            if int(third) >= 1:
                query = MallGoodsInfo.objects.filter(goods_id = i.goods_id).first()
                newdist['img'] = __imagehttpbase__ + str(query.goods_cover_img)
                newdist['id'] = i.goods_id
                if int(third) >= 3:
                    newdist['original_price'] = query.original_price
                    newdist['selling_price'] = query.selling_price
                if int(third) >= 4:
                    newdist['stock_num'] = query.stock_num
            newlist.append(newdist)
        return JsonResponse({'status': 200, 'data': newlist, 'message': 'ok'}, safe=False)


class DetailViewSet(viewsets.ModelViewSet):
    serializer_class = MallGoodsInfoSerializer
    @action(methods=['GET'], detail=False, url_name='Detail')
    def defined(self, request, id):
        query = MallGoodsInfo.objects.filter(goods_id=id).first()
        if query:
            newdist = {}
            newdist['img'] = __imagehttpbase__ + str(query.goods_cover_img)
            newdist['price'] = query.selling_price
            newdist['name'] = query.goods_name
            newdist['content'] = query.goods_detail_content
            newdist['intro'] = query.goods_intro
            newdist['stock_num'] = query.stock_num
            return JsonResponse({'status': 200, 'data': newdist, 'message': 'ok'}, safe=False)
        else:
            return JsonResponse({'status': 502, 'data': [], 'message': '查询出现问题请联系管理员！'})


class OrderinfoViewSet(viewsets.ModelViewSet):
    serializer_class = MallOrderSerializer
    @action(methods=['POST'], detail=False, url_name='Orderinfo')
    def defined(self, request, goodsid, nick, num, paytpye):
        try:
            querygi = MallGoodsInfo.objects.filter(goods_id=goodsid).first()
            queryus = MallUser.objects.filter(nick_name=nick).first()
            query = MallOrder.objects.create(order_no=goodsid, user_id=queryus.user_id, total_parice=querygi.selling_price*num, pay_type=paytpye)
            if query:
                return JsonResponse({'status': 201, 'message': 'ok'})
            else:
                raise
        except:
            return JsonResponse({'status': 555, 'message': '出现问题请联系管理员！'})


class CartViewSet(viewsets.ModelViewSet):
    serializer_class = MallCartSerializer
    @action(methods=['POST'], detail=False, url_name='cart')
    def defined(self, request, goodsid, nick, num):
        try:
            queryus = MallUser.objects.filter(nick_name=nick).first()
            query = MallCart.objects.create(goods_id=int(goodsid), user_id=queryus.user_id, goods_count=num, is_deleted=0, create_time=newDate(), update_time=newDate())
            if query:
                return JsonResponse({'status': 201, 'message': 'ok'})
            else:
                raise
        except:
            return JsonResponse({'status': 554, 'message': '出现问题请联系管理员！'})


class getCartViewSet(viewsets.ModelViewSet):
    serializer_class = MallCartSerializer
    @action(methods=['GET'], detail=False, url_name='getcart')
    def defined(self, request, nick):
        try:
            queryus = MallUser.objects.filter(nick_name=nick).first()
            query = MallCart.objects.filter(user_id=queryus.user_id, is_deleted=0)
            newlist = []
            for i in query:
                newdist = {}
                querinfo = MallGoodsInfo.objects.filter(goods_id=i.goods_id).first()
                newdist['id'] = i.pk
                newdist['name'] = querinfo.goods_name
                newdist['price'] = querinfo.selling_price
                newdist['img'] = __imagehttpbase__ + querinfo.goods_cover_img
                newdist['num'] = i.goods_count
                newdist['checked'] = False
                newlist.append(newdist)
            return JsonResponse({'status': 200, 'data': newlist, 'message': 'ok'})
        except:
            return JsonResponse({'status': 556, 'message': '出现问题请联系管理员！'})


class goodsCartViewSet(viewsets.ModelViewSet):
    serializer_class = MallCartSerializer
    @action(methods=['PUT'], detail=False, url_name='goodsCart')
    def defined(self, request):
        try:
            data = json.loads(request.body)
            for i in data:
                MallCart.objects.filter(cart_item_id= i['id']).update(is_deleted= 1)
            return JsonResponse({'status': 202, 'message': 'ok'}, safe=False)
        except:
            return JsonResponse({'status': 554, 'message': '出现问题请联系管理员！'})

class goodsOrderViewSet(viewsets.ModelViewSet):
    serializer_class = MallOrderSerializer
    @action(methods=['POST'], detail=False, url_name='goodsOrder')
    def postorder(self, request):
        try:
            data = json.loads(request.body)
            odon = int(time.time())
            para_list = {
                "type": "alipay",
                "out_trade_no": str(odon),
                "name": "测试商品",
                "money": str(data['price']),
                "clientip": "192.168.1.100",
            }
            jguo = DO_AlyPay(para_list)
            queryus = MallUser.objects.filter(nick_name= data['nick']).first()
            query = MallOrder.objects.create(order_no= odon, user_id=queryus.user_id, total_parice= data['price'], pay_status= data['status'], pay_type= data['type'], pay_time= newDate(), order_status= data['status'], extra_info= '', is_deleted= 0, create_time= newDate(), update_time= newDate())
            for i in data['data']:
                OrderItem.objects.create(order_id= query.order_id, goods_name= i['name'], goods_cover_img= i['img'], goods_count= i['num'], selling_price= i['price'], create_time= newDate())
            return JsonResponse({'status': 201, 'data': jguo, 'out_trade_no': odon, 'message': 'ok'})
        except:
            return JsonResponse({'status': 554, 'message': '出现问题请联系管理员！'})
    @action(methods=['GET'], detail=False, url_name='goodsOrder')
    def getorder(self, request, nick):
        try:
            queryus = MallUser.objects.filter(nick_name= nick).first()
            query = MallOrder.objects.filter(user_id= queryus.user_id, is_deleted= 0)
            newlist = []
            for i in query:
                newdist = {}
                newdist['price'] = i.total_parice
                newdist['status'] = i.order_status
                newlist.append(newdist)
            return JsonResponse({'status': 200,'data': newlist, 'message': 'ok'})
        except:
            return JsonResponse({'status': 554, 'message': '出现问题请联系管理员！'})

